package org.vt.ece4564.pcw.textinclass;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.util.Log;

public class LoadContacts extends AsyncTask<Void, Void, Void> {
	
	private PostContactsActivity postContactsActivity_;
	
	private List<String> nameList_ = new ArrayList<String>();
	private List<String> numberList_ = new ArrayList<String>();
	
	public LoadContacts(PostContactsActivity postContactsActivity) {
		postContactsActivity_ = postContactsActivity;
	}

	@Override
	protected Void doInBackground(Void... params) {
		
		Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
								ContactsContract.CommonDataKinds.Phone.NUMBER};

		String orderBy = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
		
		Cursor cursor = postContactsActivity_.getContentResolver().query(uri, projection,
																			null, null, orderBy);
		
		int indexName = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
		int indexNumber = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
		
		 while(cursor.moveToNext()) {
			String name = cursor.getString(indexName);
			String number = cursor.getString(indexNumber);
			
			if (!nameList_.contains(name)) {
				nameList_.add(name);
				numberList_.add(number);
				Log.d("Name", name);
			}
		}
		
		cursor.close();

		return null;

	}
	
	@Override
	protected void onPostExecute(Void result) {
		postContactsActivity_.setContacts(nameList_, numberList_);
	}

}
